package com.xhwl.centiotdata.suppliersystem.haikang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.HaiKangConstant;
import com.xhwl.centiotdata.pojo.dto.haikang.PedestrianRecordHaiKangDTO;
import com.xhwl.centiotdata.pojo.dto.haikang.PedestrianVisitorHaiKangDTO;
import com.xhwl.centiotdata.pojo.dto.haikang.VisitorInfoHaikangDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IVisitorCentService;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.visitor.VisitorGroupListDTO;
import com.xhwl.common.dto.cent.visitor.VisitorInfoDTO;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.query.cent.visitor.VisitorQRCodeQuery;
import com.xhwl.common.utils.ChkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author pengjunming
 * @description
 * @date 2022/6/10 17:10
 */
@Service
@Slf4j
public class VistorHaikangHandlerV2 {

    @Autowired
    private GeneralHaiKangHandler generalHaiKangHandler;
    @Autowired
    private IVisitorCentService visitorCentService;

    public ResultJson createVistorAuth(VisitorInfoHaikangDTO vis, VisitorIntegrationConfigDTO configDTO) {
        //预约
        try {
            JSONObject jsonResult = generalHaiKangHandler.post(HaiKangConstant.VISITOR_APPOINTMENT_URL, vis, configDTO.getProjectId(), configDTO.getProductId(),
                    configDTO.getIpAndPort(), configDTO.getAk(), configDTO.getSk(), configDTO.getTagId());
            if ("0".equals(jsonResult.getString("code"))) {
                return ResultJson.fail(jsonResult.getString("msg"));
            }
            JSONArray data = jsonResult.getJSONArray("appointmentInfoList");
            if (Objects.nonNull(data)) {
                data.forEach(t -> {
                    JSONObject obj = (JSONObject) t;
                    //登记
                    Map<String, Object> param = new HashMap<>();
                    param.put("orderId", obj.getString("orderId"));
                    param.put("visitEndTime", vis.getVisitEndTime());
                    generalHaiKangHandler.post(HaiKangConstant.REGISTER_URL, param, configDTO.getProjectId(), configDTO.getProductId(),
                            configDTO.getIpAndPort(), configDTO.getAk(), configDTO.getSk(), configDTO.getTagId());
                });
            }
            JSONObject obj = (JSONObject) data.get(0);
            Map<String, String> map = new HashMap<>();
            map.put("openId", obj.getString("orderId"));
            map.put("appointRecordId", jsonResult.getString("appointRecordId"));
            return ResultJson.success("预约成功", map);
        } catch (Exception e) {
            log.error("访客预约异常:", e);
            return ResultJson.fail("预约失败");
        }

    }

    // 拉取访客权限组
    public List<VisitorGroupListDTO> pullVisitorPrivilegeGroup(VisitorIntegrationConfigDTO configDTO, String groupName) {
        List<VisitorGroupListDTO> groupList = new LinkedList<>();
        Integer pageNum = 1;
        List<VisitorGroupListDTO> recordList = null;
        do {
            recordList = requestGroup(configDTO, groupName, pageNum);
            if (ChkUtil.isNotNull(recordList)) {
                groupList.addAll(recordList);
            }
        } while (!CollectionUtils.isEmpty(recordList) && recordList.size() >= 500);
        visitorCentService.saveVisitorPrivilegeGroup(groupList,configDTO.getProjectId(),configDTO.getProductId());
        return groupList;
    }

    private List<VisitorGroupListDTO> requestGroup(VisitorIntegrationConfigDTO configDTO, String groupName, Integer no) {
        Map<String, Object> params = new HashMap<>(5);
        params.put("pageNo", no);
        params.put("pageSize", 500);
        params.put("name", groupName);
        JSONObject dataObject = this.post(HaiKangConstant.VISITOR_PRIVILEGE_GROUP_URL, params, configDTO);
        log.info("拉取海康访客数据 - 参数：{}，结果：{}", JSON.toJSONString(params), dataObject.toJSONString());
        JSONArray list = dataObject.getJSONArray("list");
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<VisitorGroupListDTO> results = new LinkedList<>();
        List<VisitorGroupListDTO> translates = list.toJavaList(VisitorGroupListDTO.class);
        for (VisitorGroupListDTO translate : translates) {
            VisitorGroupListDTO target = new VisitorGroupListDTO();
            BeanUtils.copyProperties(translate, target);
            results.add(target);
        }
        return results;
    }

    // 拉取人行记录
    public List<PedestrianRecordHaiKangDTO> pullVisitor(VisitorIntegrationConfigDTO configDTO, List<DeviceDTO> devices, Date date) {
        List<PedestrianRecordHaiKangDTO> records = new LinkedList<>();
        if (ChkUtil.isNotNull(devices)) {
            for (DeviceDTO device : devices) {
                Integer pageNum = 1;
                List<PedestrianRecordHaiKangDTO> recordList = null;
                do {
                    recordList = requestVisitor(configDTO, device, date, pageNum);
                    if (ChkUtil.isNotNull(recordList)) {
                        records.addAll(recordList);
                    }
                } while (!CollectionUtils.isEmpty(recordList) && recordList.size() >= 500);
            }
        }
        return records;
    }

    private List<PedestrianRecordHaiKangDTO> requestVisitor(VisitorIntegrationConfigDTO configDTO, DeviceDTO device, Date date, Integer no) {
        Map<String, Object> params = new HashMap<>(5);
        params.put("pageNo", no);
        params.put("pageSize", 500);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        params.put("eventTimeBegin", sdf.format(date));
        params.put("resourceCode", device.getThirdDeviceId());

        JSONObject dataObject = this.post(HaiKangConstant.DOOR_VISITOR_URL, params, configDTO);
        log.info("拉取海康访客数据 - 参数：{}，结果：{}", JSON.toJSONString(params), dataObject.toJSONString());
        JSONArray list = dataObject.getJSONArray("rows");
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<PedestrianRecordHaiKangDTO> results = new LinkedList<>();
        List<PedestrianVisitorHaiKangDTO> translates = list.toJavaList(PedestrianVisitorHaiKangDTO.class);
        for (PedestrianVisitorHaiKangDTO translate : translates) {
            PedestrianRecordHaiKangDTO target = new PedestrianRecordHaiKangDTO();
            BeanUtils.copyProperties(translate, target);
            target.setInAndOutType(device.getName().contains("进口") ? 1 : 0);
            results.add(target);
        }
        return results;
    }

    public ResultJson cancelVistor(VisitorInfoDTO infoDTO, VisitorIntegrationConfigDTO configDTO) {
        List<String> openIdList = new ArrayList<>();
        openIdList.add(infoDTO.getAppointRecordId());
        //预约
        try {
            JSONObject jsonResult = generalHaiKangHandler.post(HaiKangConstant.VISITOR_APPOINTMENT_CANCEL_URL, openIdList, configDTO.getProjectId(), configDTO.getProductId(),
                    configDTO.getIpAndPort(), configDTO.getAk(), configDTO.getSk(), configDTO.getTagId());
            if ("0".equals(jsonResult.getString("code"))) {
                return ResultJson.success(jsonResult.getString("msg"));
            }
            return ResultJson.fail(jsonResult.getString("msg"));
        } catch (Exception e) {
            log.error("访客预约异常:", e);
            return ResultJson.fail("预约失败");
        }
    }



    // 访客签离
    public ResultJson leaveVisitor(VisitorInfoDTO infoDTO, VisitorIntegrationConfigDTO configDTO) {
        List<String> orderIdList = new ArrayList<>();
        orderIdList.add(infoDTO.getOpenId());
        //预约
        try {
            JSONObject jsonResult = generalHaiKangHandler.post(HaiKangConstant.VISITOR_APPOINTMENT_OUT_URL, orderIdList, configDTO.getProjectId(), configDTO.getProductId(),
                    configDTO.getIpAndPort(), configDTO.getAk(), configDTO.getSk(), configDTO.getTagId());
            if ("0".equals(jsonResult.getString("code"))) {
                return ResultJson.success(jsonResult.getString("msg"));
            }
            return ResultJson.fail(jsonResult.getString("msg"));
        } catch (Exception e) {
            log.error("访客预约异常:", e);
            return ResultJson.fail("预约失败");
        }
    }

    // 二维码
    public ResultJson visitorQRCode(VisitorQRCodeQuery infoDTO, VisitorIntegrationConfigDTO configDTO) {
        //预约
        try {
            JSONObject jsonResult = generalHaiKangHandler.post(HaiKangConstant.VISITOR_AUTH_QRCODE_URL, infoDTO, configDTO.getProjectId(), configDTO.getProductId(),
                    configDTO.getIpAndPort(), configDTO.getAk(), configDTO.getSk(), configDTO.getTagId());
            log.info("jsonResult"+jsonResult);
            if ("0".equals(jsonResult.getString("code"))) {
                return ResultJson.success(jsonResult.getString("data"));
            }
            return ResultJson.fail(jsonResult.getString("msg"));
        } catch (Exception e) {
            log.error("访客预约异常:", e);
            return ResultJson.fail("预约失败");
        }
    }

    private JSONObject post(String path, Object params, VisitorIntegrationConfigDTO configDTO) {
        return generalHaiKangHandler.post(
                path,
                params,
                configDTO.getProjectId(),
                configDTO.getProductId(),
                configDTO.getIpAndPort(),
                configDTO.getAk(),
                configDTO.getSk(),
                configDTO.getTagId());
    }

}
